package cn.xqj.user.service.impl;

import cn.xqj.basic.exception.BusinessException;
import cn.xqj.basic.jwt.JwtUtils;
import cn.xqj.basic.jwt.LoginData;
import cn.xqj.basic.jwt.RsaUtils;
import cn.xqj.basic.service.impl.BaseServiceImpl;
import cn.xqj.basic.util.AjaxResult;
import cn.xqj.basic.util.HttpUtil;
import cn.xqj.basic.util.MD5Utils;
import cn.xqj.basic.util.StrUtils;
import cn.xqj.org.mapper.EmployeeMapper;
import cn.xqj.system.domain.Menu;
import cn.xqj.user.constant.WxConstants;
import cn.xqj.user.domain.Logininfo;
import cn.xqj.user.domain.User;
import cn.xqj.user.domain.Wxuser;
import cn.xqj.user.dto.BinderDto;
import cn.xqj.user.dto.LoginDto;
import cn.xqj.user.mapper.LogininfoMapper;
import cn.xqj.user.mapper.UserMapper;
import cn.xqj.user.mapper.WxuserMapper;
import cn.xqj.user.service.ILogininfoService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WxuserMapper wxuserMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private EmployeeMapper employeeMapper;



    @Override
    @Transactional
    public void add(Logininfo logininfo) {
        logininfoMapper.add(logininfo);
    }



    @Override
    @Transactional
    public void update(Logininfo logininfo) {
        logininfoMapper.update(logininfo);

    }


    @Override
    @Transactional
    public void active(Long id) {
        Logininfo logininfo = logininfoMapper.findOne(id);
        logininfo.setDisable(true);
        logininfoMapper.update(logininfo);

    }

    @Override
    @Transactional
    public Map<String, Object> loginByAccount(LoginDto loginDto) {
        String acount = loginDto.getAccount();
        String password = loginDto.getPassword();
        Integer acountType = loginDto.getAccountType();

        if (StringUtils.isEmpty(acount)) {
            throw new BusinessException("账号为空！");
        }

        if (StringUtils.isEmpty(password)) {
            throw new BusinessException("密码为空！");
        }

        if (StringUtils.isEmpty(acountType)) {
            throw new BusinessException("账号类型为空！");
        }

        Logininfo logininfo = logininfoMapper.findByAcount(loginDto);

        if (logininfo == null) {
            throw new BusinessException("账号不存在！");
        }

        if (!logininfo.getDisable()) {
            throw new BusinessException("账号已被禁用！");
        }

        String salt = logininfo.getSalt();
        String inputPassword = loginDto.getPassword();

        if (!MD5Utils.encrypByMd5(inputPassword + salt).equals(logininfo.getPassword())) {
            throw new BusinessException("密码错误！");
        }


        /*Map<String, Object> map = new HashMap<>();
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
        logininfo.setPassword(null);
        logininfo.setSalt(null);
        map.put("token",token);
        map.put("logininfo",logininfo);*/

        Map<String, Object> map = loginSuccessJwtHandler(logininfo);

        return map;
    }

    private Map<String, Object> loginSuccessJwtHandler(Logininfo logininfo) {

        LoginData loginData = new LoginData();
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        loginData.setLogininfo(logininfo);
        Map<String, Object> map = new HashMap<>();
        try {
            if (logininfo.getType() == 0) {
                List<String> permissions = employeeMapper.findSnByLogininfoId(logininfo.getId());
                List<Menu> menus = employeeMapper.loadMenusByLogininfoId(logininfo.getId());
                map.put("permissions",permissions);
                map.put("menus",menus);
                loginData.setMenus(menus);
                loginData.setPermissions(permissions);
            }
            PrivateKey privateKey = RsaUtils.getPrivateKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());

            String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 30);
            map.put("token",jwtToken);
            map.put("logininfo",logininfo);
            return map;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    @Override
    public AjaxResult loginByWechat(String code) {
        String getAccess_token = WxConstants.GET_ACK_URL.replace("APPID",WxConstants.APPID)
                .replace("SECRET",WxConstants.SECRET)
                .replace("CODE",code);

        String jsonStr = HttpUtil.httpGet(getAccess_token);

        JSONObject jsonObject = JSONObject.parseObject(jsonStr);

        String access_token = jsonObject.getString("access_token");

        String openid = jsonObject.getString("openid");

        Wxuser wxuser = wxuserMapper.findByOpenId(openid);

        if (wxuser != null && wxuser.getUserId() != null) {

            Logininfo logininfo = logininfoMapper.findLogininfoByUserId(wxuser.getUserId());



            /*Map<String, Object> map = new HashMap<>();
            String token = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
            logininfo.setPassword(null);
            logininfo.setSalt(null);
            map.put("token",token);
            map.put("logininfo",logininfo);*/

            Map<String, Object> map = loginSuccessJwtHandler(logininfo);
            return AjaxResult.me().setResultObj(map);

        } else {
            Map<String, Object> map = new HashMap<>();
            map.put("access_token",access_token);
            map.put("openid",openid);
            return AjaxResult.me().setSuccess(false).setResultObj(map);
        }
    }

    @Override
    public AjaxResult wechatBinder(BinderDto binderDto) {
        String accessToken = binderDto.getAccessToken();
        String openid = binderDto.getOpenId();
        String phone = binderDto.getPhone();
        String verifyCode = binderDto.getVerifyCode();

        // 空值校验
        if (StringUtils.isEmpty(phone)) {
            throw new BusinessException("手机号为空");
        }

        if (StringUtils.isEmpty(verifyCode)) {
            throw new BusinessException("验证码为空");
        }

        Object redisBinderCode = redisTemplate.opsForValue().get("binder:" + phone);

        if (redisBinderCode == null) {
            throw new BusinessException("验证码过期");
        }

        if (!redisBinderCode.toString().split(":")[0].equals(verifyCode.trim())) {
            throw new BusinessException("验证码错误");
        }

        // 发送请求获取用户信息

        String getWechatInfo = WxConstants.GET_USER_URL.replace("ACCESS_TOKEN",accessToken)
                .replace("OPENID",openid);


        String jsonStr = HttpUtil.httpGet(getWechatInfo);
        Wxuser wxuser = jsonStr2Wxuser(jsonStr);

        User user = userMapper.findByPhone(phone);

        // 没有这个用户时
        if (user == null) {
            user = phone2User(phone);
            Logininfo logininfo = user2Logininfo(user);
            logininfoMapper.add(logininfo);
            Long logininfoId = logininfo.getId();
            user.setLogininfo_id(logininfoId);
            userMapper.add(user);
            wxuser.setUserId(user.getId());
            wxuserMapper.add(wxuser);
        } else {

            //6.将userByPhone对象的id设置到WxUser对象中
            wxuser.setUserId(user.getId());
            //7.将WxUser对象添加到数据库
            wxuserMapper.add(wxuser);
        }






        // 免密登录
        Logininfo logininfo = logininfoMapper.findOne(user.getLogininfo_id());
        /*String token = UUID.randomUUID().toString();
        logininfo.setPassword(null);
        logininfo.setSalt(null);
        redisTemplate.opsForValue().set(token,logininfo,30,TimeUnit.MINUTES);
        Map<String,Object> map = new HashMap<>();
        map.put("token",token);
        map.put("logininfo",logininfo);*/
        Map<String, Object> map = loginSuccessJwtHandler(logininfo);

        return AjaxResult.me().setResultObj(map);
    }

    @Override
    public void logout(String token) {
        redisTemplate.delete(token);
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        return logininfo;
    }

    private User phone2User(String phone) {
        User user = new User();
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        String password = StrUtils.getRandomString(6);
        user.setSalt(salt);
        user.setPassword(MD5Utils.encrypByMd5(salt+password));
        return user;
    }

    private Wxuser jsonStr2Wxuser(String jsonStr) {
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        Wxuser wxuser = new Wxuser();
        wxuser.setOpenid(jsonObject.getString("openid"));
        wxuser.setNickname(jsonObject.getString("nickname"));
        wxuser.setSex(jsonObject.getInteger("sex"));
        wxuser.setAddress(jsonObject.getString("country") + jsonObject.getString("province") + jsonObject.getString("city"));
        wxuser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxuser.setUnionid(jsonObject.getString("unionid"));
        return wxuser;
    }
}
